import NProgress from 'nprogress'

let requestCount = 0;

function startProgress() {
  if (requestCount === 0) {
    NProgress.configure({ trickleSpeed: 200, minimum: 0.1 });
    NProgress.start();
  }
  requestCount++;
}

function doneProgress() {
  requestCount--;
  if (requestCount <= 0) {
    NProgress.done();
    requestCount = 0;
  }
}

async function singleRequest(input, info) {
  startProgress();
  try {
    const response = await fetch(input, info);
    if (!response.body) return response;
    const reader = response.body.getReader();
    const contentLength = +(response.headers.get('Content-Length') || 0);
    let received = 0;
    const chunks = [];
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      chunks.push(value);
      received += value.length;
      NProgress.set(contentLength ? received / contentLength : 0.3);
    }
    return new Response(new Blob(chunks), { status: response.status, headers: response.headers });
  } finally {
    doneProgress();
  }
}

export default async function request(inputs, info) {
  if (Array.isArray(inputs)) {
    if (inputs.length === 1) {
      const res = await singleRequest(inputs[0].url, inputs[0].info || info);
      return res.json();
    }
    const responses = await Promise.all( inputs.map(item => singleRequest(item.url, item.info)) );
    return Promise.all(responses.map(res => res.json()));
  } else {
    const res = await singleRequest(inputs, info || info);
    return res.json();
  }
}